<template>
  <div ref="containerRef" class="custom-table-container">
    <el-row :gutter="20">
      <el-col :lg="6" :md="8" :sm="24" :xl="4" :xs="24">
        <vab-card shadow="hover">
          <el-tree
            ref="treeRef"
            :data="treeList"
            :default-expanded-keys="[0]"
            :expand-on-click-node="false"
            node-key="corp_id"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </vab-card>
      </el-col>
      <el-col :lg="18" :md="16" :sm="24" :xl="20" :xs="24">
        <vab-query-form>
          <vab-query-form-left-panel>
            <el-button :icon="Plus" type="primary" @click="handleAdd">
              创建链接
            </el-button>
          </vab-query-form-left-panel>
          <vab-query-form-right-panel>
            <div class="stripe-panel">
              <el-checkbox v-model="stripe">斑马纹</el-checkbox>
            </div>
            <div class="border-panel">
              <el-checkbox v-model="border">边框（可拉伸列）</el-checkbox>
            </div>
            <el-button
              class="but_text"
              style="margin: 0 10px 10px 0 !important"
              text
              type="primary"
              @click="clickFullScreen"
            >
              <vab-icon
                :icon="
                  isFullscreen ? 'fullscreen-exit-fill' : 'fullscreen-fill'
                "
              />
            </el-button>
            <el-popover popper-class="custom-table-radio" trigger="hover">
              <el-radio-group v-model="lineHeight">
                <el-radio label="large">大</el-radio>
                <el-radio label="default">中</el-radio>
                <el-radio label="small">小</el-radio>
              </el-radio-group>
              <template #reference>
                <el-button
                  class="but_text"
                  style="margin: 0 10px 10px 0 !important"
                  text
                  type="primary"
                >
                  <vab-icon icon="line-height" />
                </el-button>
              </template>
            </el-popover>
            <el-popover popper-class="custom-table-checkbox" trigger="hover">
              <template #reference>
                <el-button
                  class="but_text"
                  style="margin: 0 0 10px 0 !important"
                  text
                  type="primary"
                >
                  <vab-icon icon="settings-line" />
                </el-button>
              </template>
              <el-checkbox-group v-model="checkList">
                <vab-draggable
                  v-bind="dragOptions"
                  item-key="{ element }"
                  :list="columns"
                >
                  <template #item="{ element }">
                    <div>
                      <vab-icon icon="drag-drop-line" />
                      <el-checkbox
                        :disabled="element.disableCheck === true"
                        :label="element.label"
                      >
                        {{ element.label }}
                      </el-checkbox>
                    </div>
                  </template>
                </vab-draggable>
              </el-checkbox-group>
            </el-popover>
          </vab-query-form-right-panel>
        </vab-query-form>
        <el-table
          v-loading="listLoading"
          :border="border"
          :data="list"
          :height="height"
          :size="lineHeight"
          :stripe="stripe"
        >
          <!--  TODO element-plus未知原因不支持拖拽后宽度重新计算，暂时放弃 -->
          <el-table-column
            v-for="(item, index) in finallyColumns"
            :key="index"
            align="center"
            :label="item.label"
            min-width="115"
            :prop="item.prop"
            :show-overflow-tooltip="true"
            :sortable="item.sortable"
            width="auto"
          >
            <template #default="{ row }">
              <span v-if="item.prop == 'order_type'">
                {{ orderTypeFilter(row[item.prop]) }}
              </span>
              <span v-else>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="210"
          >
            <template #default="{ row }">
              <el-button
                class="but_text"
                text
                type="primary"
                @click="handleCopy(row)"
              >
                复制链接
              </el-button>
              <el-button
                class="but_text"
                text
                type="primary"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty class="vab-data-empty" description="暂无成员" />
          </template>
        </el-table>
        <div class="load-more">
          <el-button
            :loading="listLoading"
            style="font-size: 16px; font-weight: bold"
            text
            type="primary"
            @click="loadMore"
          >
            点击加载更多
          </el-button>
        </div>
      </el-col>
    </el-row>
    <edit ref="editRef" @fetch-data="fetchData('init')" />
  </div>
</template>

<script>
  import { getWechatAll } from '@/api/enterpriseWeChat/weCom'
  import { getLinkList, linkDelete } from '@/api/enterpriseWeChat/link'
  import VabDraggable from 'vuedraggable'
  import { Delete, Plus, Search, Setting } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'LinkList',
    components: {
      Edit: defineAsyncComponent(() => import('./components/TableEdit')),
      VabDraggable,
    },
    setup() {
      const route = useRoute()
      const router = useRouter()
      const $baseMessage = inject('$baseMessage')
      const $baseConfirm = inject('$baseConfirm')
      const $baseTableHeight = inject('$baseTableHeight')

      const state = reactive({
        editRef: null,
        treeRef: null,
        border: true,
        height: $baseTableHeight(1),
        stripe: true,
        lineHeight: 'default',
        treeList: [
          {
            corp_id: 0,
            corp_name: '企业',
            children: [],
          },
        ],
        defaultProps: {
          children: 'children',
          label: 'corp_name',
        },
        checkList: ['订单ID', '链接名称', '链接', '创建时间'],
        columns: [
          {
            label: '链接ID',
            prop: 'link_id',
          },
          {
            label: '链接名称',
            prop: 'link_name',
          },
          {
            label: '链接',
            prop: 'url',
          },
          {
            label: '创建时间',
            prop: 'create_time',
          },
        ],
        orderTypeList: [
          { id: 1, name: '购买账号' },
          { id: 2, name: '续期账号' },
          { id: 5, name: '历史企业迁移订单' },
          { id: 8, name: '多企业新购订单' },
        ],
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        corp_name: '',
        queryForm: {
          corp_id: null,
          next_cursor: null,
          limit: 20,
        },
      })

      const dragOptions = computed(() => {
        return {
          animation: 600,
          group: 'description',
        }
      })
      const finallyColumns = computed(() => {
        return state.columns.filter((item) =>
          state.checkList.includes(item.label)
        )
      })
      const listData = async () => {
        const { data } = await getWechatAll()
        state.treeList[0].children = data
        console.log(data)
        if (data) {
          handleNodeClick({
            corp_id: data[0].corp_id,
            corp_name: data[0].corp_name,
          })
        }
      }
      const fetchData = async (edit) => {
        if (edit) {
          state.list = []
          state.queryForm.next_cursor = null
        }
        state.listLoading = true
        const { data } = await getLinkList(state.queryForm)
        console.log(data)
        if (data.list) {
          state.list = [...state.list, ...data.list]
          state.queryForm.next_cursor = data.next_cursor
        }
        state.listLoading = false
      }
      const queryData = () => {
        fetchData()
      }

      const containerRef = ref(null)
      const { toggle, isFullscreen } = useFullscreen(containerRef)
      const clickFullScreen = () => {
        toggle().then(() => {
          handleHeight()
        })
      }
      const handleHeight = () => {
        if (isFullscreen.value) state.height = $baseTableHeight(1) + 356
        else state.height = $baseTableHeight(1)
      }
      const handleNodeClick = (row) => {
        console.log(row)
        if (row.corp_id != 0) {
          state.queryForm.corp_id = row.corp_id
          state.corp_name = row.corp_name
          state.list = []
          fetchData()
        }
      }
      const handleCopy = ({ url }) => {
        const oInput = document.createElement('input')
        oInput.value = url
        document.body.appendChild(oInput)
        oInput.select()
        document.execCommand('Copy')
        $baseMessage('复制成功', 'success', 'vab-hey-message-success')
        oInput.remove()
      }
      const handleDelete = ({ link_id }) => {
        if (link_id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { message } = await linkDelete({
              corp_id: state.queryForm.corp_id,
              link_id: link_id,
            })
            $baseMessage(message, 'success', 'vab-hey-message-success')
            await fetchData('init')
          })
        }
      }
      const handleAdd = () => {
        state['editRef'].showEdit(state.queryForm.corp_id)
      }
      const orderTypeFilter = (id) => {
        console.log(id)
        if (id == null) return ''
        let departName = ''
        state.orderTypeList.forEach((item) => {
          if (item.id == id) {
            departName = item.name
          }
        })
        return departName
      }
      const loadMore = () => {
        fetchData()
      }
      onMounted(async () => {
        await listData()
      })

      return {
        ...toRefs(state),
        dragOptions,
        containerRef,
        isFullscreen,
        finallyColumns,
        queryData,
        handleHeight,
        clickFullScreen,
        fetchData,
        handleCopy,
        handleDelete,
        handleAdd,
        orderTypeFilter,
        Plus,
        Delete,
        Search,
        Setting,
        handleNodeClick,
        loadMore,
      }
    },
  })
</script>
<style lang="scss" scoped>
  @use 'sass:math';
  .load-more {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
  .custom-table-container {
    :deep() {
      i {
        cursor: pointer;
      }
    }

    .right-panel {
      .stripe-panel,
      .border-panel {
        margin: 0 10px #{math.div($base-margin, 2)} 10px !important;

        :deep() {
          .el-checkbox__label {
            margin-left: 0 !important;
          }
        }
      }

      [class*='ri'] {
        font-size: $base-font-size-big;
        color: var(--el-color-black);
      }
    }
  }
</style>
<style lang="scss">
  html body .custom-table-checkbox {
    [class*='ri'] {
      vertical-align: -0.5px !important;
      cursor: pointer;
    }

    .el-checkbox {
      margin: 5px 0 5px 8px;
    }
  }

  .custom-table-radio {
    width: 240px !important;
  }
</style>
